import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Product } from '@/types'

export const useCartStore = defineStore(
  'cart',
  () => {
    const cartList = ref<any>([])

    // 更新购物车
    const updateCart = (product: Product) => {
      const currentCount = product.count ?? 0
      // 判断购物车中是否存在该商品
      const itemIndex = cartList.value.findIndex((item: any) => item.id === product.id)
      // 数量有效时的处理逻辑
      if (currentCount > 0) {
        if (itemIndex === -1) {
          // 首次添加：创建新对象避免引用污染，并确保count存在
          cartList.value.push({
            ...product,
          })
        } else {
          // 更新已存在商品的数量
          cartList.value[itemIndex].count = currentCount
        }
      }
      // 数量归零或无效时的处理逻辑
      else {
        // 从购物车移除商品
        if (itemIndex !== -1) cartList.value.splice(itemIndex, 1)
      }
    }

    // 清空购物车
    const clearCart = () => {
      cartList.value = []
    }

    // 获取被选中的商品数量
    const getSelectedCount = () => {
      return cartList.value.reduce((acc: number, cur: any) => {
        if (cur.isSelected) {
          acc += cur.count
        }
        return acc
      }, 0)
    }

    // 获取被选中的商品的长度
    const getSelectedProducts = () => {
      return cartList.value.filter((item: any) => item.isSelected).length
    }

    // 获取被选中的商品
    const getSelectedProductsList = () => {
      return cartList.value.filter((item: any) => item.isSelected)
    }

    // 获取被选中的商品价格
    const getSelectedProductPrice = () => {
      if (cartList.value.length) {
        return cartList.value
          .filter((item: Product) => item.isSelected)
          .reduce((total: number, item: any) => total + item.price * item.count, 0)
          .toFixed(2)
      }
      return 0
    }

    // 更新购物车被选中的状态
    const updateSelectedStatus = (id: number, status: boolean) => {
      const itemIndex = cartList.value.findIndex((item: any) => item.id === id)
      if (itemIndex !== -1) {
        cartList.value[itemIndex].isSelected = status
      }
    }

    // 删除购物车中的某一个商品
    const deleteProduct = (id: number) => {
      const itemIndex = cartList.value.findIndex((item: any) => item.id === id)
      if (itemIndex !== -1) {
        cartList.value.splice(itemIndex, 1)
      }
    }

    // 删除被选中的商品
    const deleteSelectedProducts = () => {
      cartList.value = cartList.value.filter((item: any) => !item.isSelected)
    }

    return {
      cartList,
      clearCart,
      updateCart,
      deleteProduct,
      getSelectedCount,
      getSelectedProducts,
      getSelectedProductPrice,
      updateSelectedStatus,
      getSelectedProductsList,
      deleteSelectedProducts,
    }
  },
  // TODO: 持久化
  {
    // 配置持久化
    persist: {
      // 调整为兼容多端的API
      storage: {
        setItem(key, value) {
          uni.setStorageSync(key, value)
        },
        getItem(key) {
          return uni.getStorageSync(key)
        },
      },
    },
  },
)
